<template>
  <!-- 注册页面主容器 -->
  <div class="register-container">
    <!-- 注册表单卡片 -->
    <el-card class="register-card">
      <!-- 卡片头部 -->
      <template #header>
        <div class="card-header">
          <h2>注册账户</h2>
        </div>
      </template>

      <!-- 注册表单 -->
      <el-form 
        :model="registerForm" 
        :rules="rules" 
        ref="registerFormRef"
        label-position="top"
        @submit.prevent="completeRegistration"
      >
        <!-- 用户名输入框 -->
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="registerForm.username" 
            placeholder="请输入用户名"
            clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 手机号输入框 -->
        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="registerForm.phone" 
            placeholder="请输入手机号" 
            maxlength="11"
            clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 验证码输入区域 -->
        <el-form-item label="验证码" prop="captcha">
          <div class="captcha-input">
            <!-- 验证码输入框 -->
            <el-input 
              v-model="registerForm.captcha" 
              placeholder="请输入验证码"
              clearable
            >
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
            <!-- 发送验证码按钮 -->
            <el-button 
              type="primary" 
              :disabled="isCountingDown"
              @click="sendCaptcha"
              class="captcha-btn"
            >
              {{ countdownText }}
            </el-button>
          </div>
        </el-form-item>

        <!-- 密码输入框 -->
        <el-form-item label="设置密码" prop="password">
          <el-input 
            v-model="registerForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
            clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 确认密码输入框 -->
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码"
            show-password
            clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button 
            type="primary" 
            native-type="submit" 
            class="submit-btn"
            :loading="isSubmitting"
          >
            完成注册
          </el-button>
        </el-form-item>

        <!-- 登录链接 -->
        <div class="login-link">
          <span>已有账户？</span>
          <el-link type="primary" @click="$router.push('/login')">立即登录</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { User, Message, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'  // 添加这行导入

export default {
  // 注册需要使用的图标组件
  components: {
    User,
    Message,
    Lock
  },
  setup() {
    const router = useRouter()
    // 表单引用
    const registerFormRef = ref(null)
    // 提交状态标志
    const isSubmitting = ref(false)
    // 验证码倒计时状态
    const isCountingDown = ref(false)
    const countdown = ref(60)
    const countdownText = ref('发送验证码')

    // 注册表单数据
    const registerForm = reactive({
      username: '',
      phone: '',
      captcha: '',
      password: '',
      confirmPassword: ''
    })

    // 用户名验证规则
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入用户名'))
      } else if (value.length < 3 || value.length > 20) {
        callback(new Error('用户名长度在3到20个字符'))
      } else {
        callback()
      }
    }

    // 确认密码验证规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }

    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }

    // 表单验证规则集合
    const rules = reactive({
      username: [
        { validator: validateUsername, trigger: 'blur' }
      ],
      phone: [
        { validator: validatePhone, trigger: 'blur' }
      ],
      captcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { validator: validateConfirmPassword, trigger: 'blur' }
      ]
    })

    // 发送验证码方法
    const sendCaptcha = () => {
      // 先验证手机号
      registerFormRef.value.validateField('phone', async (valid) => {
        if (valid) {
          isCountingDown.value = true
          
          try {
            const response = await axios.post('/api/users/send-code/', {
              scene: 'register',
              phone: registerForm.phone
            })
            
            if (response.data.status === 'success') {
              ElMessage.success('验证码已发送')
              // 开始倒计时
              const timer = setInterval(() => {
                if (countdown.value <= 0) {
                  clearInterval(timer)
                  isCountingDown.value = false
                  countdown.value = 60
                  countdownText.value = '发送验证码'
                } else {
                  countdown.value--
                  countdownText.value = `${countdown.value}秒后重发`
                }
              }, 1000)
            } else {
              ElMessage.error(response.data.message || '发送验证码失败')
              isCountingDown.value = false
            }
          } catch (error) {
            ElMessage.error('网络错误，请稍后重试')
            isCountingDown.value = false
          }
        }
      })
    }

    // 提交注册方法
    const completeRegistration = async () => {
      registerFormRef.value.validate(async (valid) => {
        if (valid) {
          isSubmitting.value = true;
          
          try {
            const response = await axios.post('/api/users/register/', {
              username: registerForm.username,
              phone: registerForm.phone,
              captcha: registerForm.captcha,
              password: registerForm.password,
            });

            if (response.data.status === 'success') {
              ElMessage.success('注册成功');
              router.push('/login');
            } else {
              ElMessage.error(response.data.message || '注册失败');
            }
          } catch (error) {
            if (error.response) {
              ElMessage.error(error.response.data.message || '注册失败');
            } else {
              ElMessage.error('网络错误，请稍后重试');
            }
          } finally {
            isSubmitting.value = false;
          }
        }
      });
    }

    return {
      registerFormRef,
      registerForm,
      rules,
      isSubmitting,
      isCountingDown,
      countdownText,
      sendCaptcha,
      completeRegistration
    }
  }
}
</script>

<style scoped>
/* 注册页面容器样式 */
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

/* 注册卡片样式 */
.register-card {
  width: 100%;
  max-width: 450px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 卡片头部样式 */
.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

/* 验证码输入区域样式 */
.captcha-input {
  display: flex;
  gap: 10px;
}

/* 验证码按钮样式 */
.captcha-btn {
  width: 120px;
}

/* 提交按钮样式 */
.submit-btn {
  width: 100%;
  margin-top: 10px;
}

/* 登录链接样式 */
.login-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #606266;
}

.login-link span {
  margin-right: 5px;
}
</style>